<?php

use App\Services\EncodeIdService;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;


function infoArray($info = [], $follow_id = [], $chooes_id = [])
{
    if (empty($info) && empty($follow_id)) {
        return [];
    }

    foreach ($info as $key => $val) {

        if (in_array($val['id'], $follow_id)) {

            $info[$key]['is_follow'] = 1;
        } else {
            $info[$key]['is_follow'] = 0;
        }
    }

    // if($chooes_id){
    foreach ($info as $key => $val) {
        if (in_array($val['id'], $chooes_id)) {

            $info[$key]['is_chooes'] = 1;
        } else {

            $info[$key]['is_chooes'] = 0;
        }
    }
    // }

    return $info;
}

/**
 * 获取用户id
 *
 * @Author hechengwei
 * @email chichiooo@sina.com
 * @DateTime 2022-04-14
 * @return void
 */
function userId()
{
    return auth('api')->id();
}


function user()
{
    return auth('api')->user();
}


function or_url($url)
{
    if (empty($url)) {
        return true;
    }
    $preg = "/http[s]?:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is";

    if (preg_match($preg, $url)) {
        return true;
    } else {

        return false;
    }
}

function infoLog($e)
{
    Log::info($e);
}


function noticeLog($e)
{
    Log::notice($e);
}


function responses($message = '', $data = [], $code = 200)
{
    $result['data'] = $data;


    $result['data'] = $data;

    $result['code'] = $code;

    $result['message'] = $message;
    return response()->json($result)->header('Content-Type', 'application/json;charset=UTF-8')->setEncodingOptions(JSON_UNESCAPED_UNICODE);
}

function success($data = [], $message = '操作成功', $code = 200)
{
    return responses($message, $data, $code);
}


function fail($data = [], $message = '操作失败', $code = 422)
{
    return responses($message, $data, $code);
}

function fail_message($message = '操作失败')
{
    throw new HttpResponseException(fail([], $message));
}

function success_message($message = '操作成功')
{
    return success([], $message);
}



/**
 * 成功分页返回
 * @param $page
 * @return JsonResponse
 */
function successPaginate($page): JsonResponse
{
    return success(paginate($page));
}

function paginate($page)
{
    if ($page instanceof LengthAwarePaginator) { //LengthAwarePaginator
        return [
            'total'  => $page->total(),
            'page'   => $page->currentPage(),
            'limit'  => $page->perPage(),
            'pages'  => $page->lastPage(),
            'list'   => $page->items()
        ];
    }
    if ($page instanceof Collection) { //Collection
        $page = $page->toArray();
    }
    if (!is_array($page)) {
        return $page;
    }
    $total = count($page);
    return [
        'total'  => $total, //数据总数
        'page'   => 1, // 当前页码
        'limit'  => $total, // 每页的数据条数
        'pages'  => 1, // 最后一页的页码
        'list'   => $page // 数据
    ];
}


function stringToId($string)
{
    $obj = new EncodeIdService();
    return $obj->stringToId($string);
}

function idToString($id)
{
    $obj = new EncodeIdService();
    return $obj->idToString($id);
}


/**
 * 下载远程文件到本地文件夹 \storage\app\public
 *
 * @Author hechengwei
 * @email chichiooo@sina.com
 * @DateTime 2022-08-15
 * @param string $url
 * @param [type] $savePath  文件夹分类
 * @return void
 */
function downloadFile($url = '', $savePath = '')
{
    if (empty($url)) {
        return [];
    }

    $client = new \GuzzleHttp\Client(['verify' => false]);
    $file_name = pathinfo($url)['basename'];
    $file_temp_path = $savePath . '/' . date('Y-m-d') . '/' . $file_name; //保存文件地址+原始文件名

    $tempData = $client->request('get', $url)->getBody()->getContents();

    $judge = Storage::disk('public')->put($file_temp_path, $tempData); //storage/app/public/document/remoteFiles文件保存地址

    if ($judge) {
        return 'storage/app/public' . $file_temp_path;
    }
}



if (!function_exists('qnUrl')) {
    function qnUrl()
    {
        return config('filesystems.disks.qiniu.domains.https');
    }
}


/**
 * @ 0-存数字字符串；1-小写字母字符串；2-大写字母字符串；3-大小写数字字符串；4-字符；
 *   5-数字，小写，大写，字符混合
 * @param  integer $type   [字符串的类型]
 * @param  integer $length [字符串的长度]
 * @param  integer $time   [是否带时间1-带，0-不带]
 * @return [string]  $str    [返回唯一字符串]
 */
if (!function_exists('randSole')) {
    function randSole($type = 0, $length = 18, $time = 0)
    {
        $str = $time == 0 ? '' : date('YmdHis', time());
        switch ($type) {
            case 0:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $str .= rand(0, 9);
                    }
                }
                break;
            case 1:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $rand = "qwertyuioplkjhgfdsazxcvbnm";
                        $str .= $rand[mt_rand(0, 25)];
                    }
                }
                break;
            case 2:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $rand = "QWERTYUIOPLKJHGFDSAZXCVBNM";
                        $str .= $rand[mt_rand(0, 25)];
                    }
                }
                break;
            case 3:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $rand = "123456789qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM";
                        $str .= $rand[mt_rand(0, 34)];
                    }
                }
                break;
            case 4:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $rand = "!@#$%^&*()_+=-~`";
                        $str .= $rand[mt_rand(0, 16)];
                    }
                }
                break;
            case 5:
                for ((int) $i = 0; $i <= $length; $i++) {
                    if (mb_strlen($str) == $length) {
                        $str = $str;
                    } else {
                        $rand = "123456789qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM!@#$%^&*()_+=-~`";
                        $str .= $rand[mt_rand(0, 51)];
                    }
                }
                break;
        }
        return $str;
    }
}

function httpToHttps($url)
{
    return  str_replace("http://", "https://", $url);
}
